package com.csdemos.algs;

public class DoubleStack {
	
	public static final int STACK_1 = 1;
	public static final int STACK_2 = 2;
	
	private static final int INITIAL_SIZE = 10;
	
	private int[] S;
	private int top1;
	private int top2;
	
	public DoubleStack() {
		this(INITIAL_SIZE);
	}
	
	public DoubleStack(int initialSize) {
		S = new int[initialSize];
		top1 = 0;
		top2 = S.length - 1;
	}
	
	public boolean isEmpty(int stackId) {
		switch (stackId) {
			case STACK_1:
				return top1 == 0;
			case STACK_2:
				return top2 == S.length - 1;
			default:
				throw new IllegalArgumentException("You can use only 1 or 2 stack!");
		}
	}
		
	public boolean isFull() {
		return top1 == top2 + 1;
	}
	
	public void push(int stackId, int x) {
		if (isFull()) {
			throw new IllegalStateException("Stack is full!");
		}
		switch (stackId) {
			case STACK_1:
				S[top1] = x;
				top1++;
				break;
			case STACK_2:
				S[top2] = x;
				top2--;
				break;
			default:
				throw new IllegalArgumentException("You can use only 1 or 2 stack!");
		}
	}
	
	
	
	public int pop(int stackId) {
		if (isEmpty(stackId)) {
			throw new IllegalStateException("Underlow");
		}
		switch (stackId) {
		case STACK_1:
			top1--;
			return S[top1];
		case STACK_2:
			top2++;
			return S[top2];
		default:
			throw new IllegalArgumentException("You can use only 1 or 2 stack!");
		}
	}
	
	
	@Override
	public String toString() {
		StringBuilder result = new StringBuilder("[");
		for (int i = 0; i < S.length; ++i) {
			if (i == top1) {
				result.append(" t1-> ");
			}
			if (i == top2) {
				result.append(" t2-> ");
			}
			result.append(S[i]).append(" ");
		}
		return result.append("]").toString();
	}

}
